package com.yao.mygranter;

import com.yao.service.IUserCodeService;
import com.yao.service.IUserDetailsService;
import com.yao.service.pojo.UserCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.security.oauth2.common.exceptions.RedirectMismatchException;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public class DingtalkAuthTokenGranter extends AbstractTokenGranter {

    private static final String GRANT_TYPE = "dingtalk";

    private final AuthenticationManager authenticationManager;


    private  IUserCodeService userCodeService;


    private UserDetailsService userDetailsService;


    public DingtalkAuthTokenGranter(AuthenticationManager authenticationManager,
                                    AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
    }

    public DingtalkAuthTokenGranter(AuthenticationManager authenticationManager,
                                    AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,IUserCodeService userCodeService,IUserDetailsService userDetailsService,OAuth2RequestFactory requestFactory) {
        this(authenticationManager, tokenServices, clientDetailsService,userCodeService,userDetailsService, requestFactory, GRANT_TYPE);
    }

    protected DingtalkAuthTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                       ClientDetailsService clientDetailsService, IUserCodeService userCodeService,IUserDetailsService userDetailsService,OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
        this.userCodeService=userCodeService;
        this.userDetailsService=userDetailsService;
    }

    protected DingtalkAuthTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                       ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }

//    @Override
//    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
//        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
//        String code = parameters.get("code");
//        // Protect from downstream leaks of password
//        parameters.remove("code");
//        Authentication userAuth = new DingtalkAuthenticationToken(code);
//        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
//        ((DingtalkAuthenticationToken) userAuth).setParams(parameters);
//        ((DingtalkAuthenticationToken) userAuth).setTokenRequest(tokenRequest);
//        try {
//            userAuth = authenticationManager.authenticate(userAuth);
//        } catch (AccountStatusException ase) {
//            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
//            throw new InvalidGrantException(ase.getMessage());
//        } catch (BadCredentialsException e) {
//            // If the username/password are wrong the spec says we should send 400/invalid grant
//            throw new InvalidGrantException(e.getMessage());
//        }
//        if (userAuth == null || !userAuth.isAuthenticated()) {
//            throw new InvalidGrantException("Could not authenticate with dingtalk code: " + code);
//        }
//
//        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
//        return new OAuth2Authentication(storedOAuth2Request, userAuth);
//    }

    String userNameClientId="client:user:%s:%s";


    RedisTemplate<String,String> redisTemplate;

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> parameters = tokenRequest.getRequestParameters();
        String authorizationCode = parameters.get("code");
        String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);

        if (authorizationCode == null) {
            throw new InvalidRequestException("An authorization code must be supplied.");
        }



        if(!StringUtils.hasText(authorizationCode)){
            return null;
        }


        UserCode userCode = this.userCodeService.getByCode(authorizationCode);
        if(Objects.isNull(userCode)){
            throw new InvalidGrantException("Could not authenticate with dingtalk code: " + authorizationCode);
        }


        UserDetails userDetails = this.userDetailsService.loadUserByUsername(userCode.getUserName());

        if(Objects.isNull(userDetails)){
            throw new InvalidGrantException("Could not authenticate with dingtalk code: " + authorizationCode);
        }
        Authentication userAuth = new DingtalkAuthenticationToken(authorizationCode);



         userAuth = createSuccessAuthentication(userDetails, userAuth, userDetails);

        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate with dingtalk code: " + authorizationCode);
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);



        return new OAuth2Authentication(storedOAuth2Request, userAuth);

    }


    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();

    protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
        DingtalkAuthenticationToken result = new DingtalkAuthenticationToken(
                principal,
                authoritiesMapper.mapAuthorities(user.getAuthorities()));
        result.setDetails(authentication.getDetails());

        return result;
    }
}
